'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Button from '@/components/ui/Button'
import { PlusIcon, TrashIcon, UserPlusIcon, XMarkIcon } from '@heroicons/react/24/outline'
import { toast } from 'react-hot-toast'
import { getPistonRuntimes, PistonRuntime } from '@/lib/pistonService'

interface Student {
  id: string
  name: string
  email: string
}

// 新的选择题选项接口
interface ChoiceOption {
  id: string; 
  text: string;
}

// 新的选择题内容接口
interface MultipleChoiceContent {
  question: string;
  options: ChoiceOption[];
  correctAnswerId: string | null; 
  points?: number; 
  answerExplanation?: string;
  explanationVisibleToStudent?: boolean;
}

// 新的填空题内容接口
interface FillInBlankContent {
  question?: string; // 题干，可以包含 __ 表示填空处
  standardAnswers: string[]; // 标准答案列表
  matchCase?: boolean; // 是否区分大小写
  points?: number; // 分值
  answerExplanation?: string;
  explanationVisibleToStudent?: boolean;
}

// General content for other types like CODE, FILE_UPLOAD
interface GeneralStageContent {
    points?: number;
    answerExplanation?: string;
    explanationVisibleToStudent?: boolean;
}

// 新增文件上传题内容接口
interface FileUploadContent {
  prompt?: string; // 题干或提交说明与要求
  allowedFileTypes?: string; // 逗号分隔的允许文件类型, e.g., ".pdf,.docx,.zip"
  maxFileSizeMB?: number;
  points?: number;
  answerExplanation?: string;
  explanationVisibleToStudent?: boolean;
}

// 新增测试用例接口
interface TestCase {
  id: string; 
  name: string;
  input: string;
  expectedOutput: string;
  points: number;
  isHidden: boolean;
}

// 新增代码题内容接口
interface CodeStageContent {
  prompt?: string;
  language?: string;
  languageVersion?: string;
  template?: string;
  points?: number; // 总分，将由测试用例累加
  answerExplanation?: string;
  explanationVisibleToStudent?: boolean;
  testCases?: TestCase[]; // 新增测试用例
}

// 更新 Stage 接口
interface Stage {
  title: string;
  type: 'MULTIPLE_CHOICE' | 'FILL_IN_BLANK' | 'CODE' | 'FILE_UPLOAD';
  description: string; // 通用描述/说明
  content: MultipleChoiceContent | FillInBlankContent | FileUploadContent | CodeStageContent | GeneralStageContent; // 更明确的联合类型
}

const generateOptionId = () => `option_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
const generateTestCaseId = () => `testcase_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;

const calculateCodeStagePoints = (testCases: TestCase[] | undefined): number => {
  if (!testCases || testCases.length === 0) {
    return 0;
  }
  return testCases.reduce((sum, tc) => sum + (Number(tc.points) || 0), 0);
};

export default function ExperimentForm() {
  const router = useRouter()
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [startTime, setStartTime] = useState('')
  const [endTime, setEndTime] = useState('')
  const [allowLateSubmission, setAllowLateSubmission] = useState(false)
  const [stages, setStages] = useState<Stage[]>([])
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [errorMsg, setErrorMsg] = useState<string | null>(null)
  
  // 添加学生选择相关状态
  const [students, setStudents] = useState<Student[]>([])
  const [selectedStudents, setSelectedStudents] = useState<Student[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [showStudentSearch, setShowStudentSearch] = useState(false)
  
  // 获取所有学生
  useEffect(() => {
    const fetchStudents = async () => {
      try {
        const response = await fetch('/api/users?role=STUDENT')
        if (response.ok) {
          const data = await response.json()
          setStudents(data)
        } else {
          console.error('获取学生列表失败')
        }
      } catch (error) {
        console.error('获取学生列表错误:', error)
      }
    }
    
    fetchStudents()
  }, [])

  const [pistonRuntimes, setPistonRuntimes] = useState<PistonRuntime[]>([])
  const [isLoadingRuntimes, setIsLoadingRuntimes] = useState(true)

  useEffect(() => {
    async function fetchRuntimes() {
      setIsLoadingRuntimes(true)
      try {
        const runtimes = await getPistonRuntimes()
        setPistonRuntimes(runtimes)
      } catch (error) {
        console.error("获取Piston运行时失败:", error)
        // TODO: 在UI上向用户显示错误
      } finally {
        setIsLoadingRuntimes(false)
      }
    }
    fetchRuntimes()
  }, [])

  const handleAddStage = () => {
    setStages(prevStages => [
      ...prevStages,
      {
        title: '',
        type: 'CODE',
        description: '',
        content: {
          prompt: '',
          language: '',
          languageVersion: '',
          template: '// Code here',
          points: 0,
          testCases: [],
          answerExplanation: '',
          explanationVisibleToStudent: false,
        } as CodeStageContent,
      },
    ])
  }

  const handleRemoveStage = (index: number) => {
    setStages(stages.filter((_, i) => i !== index))
  }

  const handleStageChange = (
    stageIndex: number, 
    field: keyof Stage | string,
    value: any,
    testCaseIndex?: number,
    testCaseField?: keyof TestCase
  ) => {
    setStages(prevStages =>
      prevStages.map((stage, i) => {
        if (i === stageIndex) {
          const updatedStage = { ...stage };
          if (typeof field === 'string' && field.startsWith('content.')) {
            const contentField = field.substring(8);
            let newContent = { ...(stage.content || {}) } as any;

            if (stage.type === 'CODE') {
              if (!newContent.prompt && !newContent.language && !newContent.testCases) {
                  newContent = { prompt: '', language: '', languageVersion: '', testCases: [], points:0, ...newContent } as CodeStageContent;
              }

              if (contentField === 'language') {
                newContent.language = value;
                newContent.languageVersion = '';
              } else if (contentField === 'languageVersion') {
                newContent.languageVersion = value;
              } else if (contentField === 'testCases' && typeof testCaseIndex === 'number' && testCaseField) {
                let currentTestCases = Array.isArray(newContent.testCases) ? [...newContent.testCases] : [];
                if (currentTestCases[testCaseIndex]) {
                  currentTestCases[testCaseIndex] = {
                    ...currentTestCases[testCaseIndex],
                    [testCaseField]: testCaseField === 'points' ? (Number(value) || 0) : value,
                  };
                  newContent.testCases = currentTestCases;
                  newContent.points = calculateCodeStagePoints(currentTestCases);
                } else if (testCaseField) {
                }
              } else if (contentField !== 'points') {
                newContent[contentField] = value;
              }
            } else if (stage.type === 'MULTIPLE_CHOICE') {
              if (!newContent.question && !newContent.options) {
                  newContent = { question: '', options: [], correctAnswerId: null, points: 0, ...newContent } as MultipleChoiceContent;
              }
              if (contentField.startsWith('options.')) {
                const optionPath = contentField.substring(8).split('.');
                const optionIdx = parseInt(optionPath[0], 10);
                const optionProp = optionPath[1] as keyof ChoiceOption;
                let currentOptions = Array.isArray(newContent.options) ? [...newContent.options] : [];
                if (currentOptions[optionIdx]) {
                  currentOptions[optionIdx] = { ...currentOptions[optionIdx], [optionProp]: value };
                  newContent.options = currentOptions;
                }
              } else if (contentField === 'points') {
                newContent.points = Number(value) >= 0 ? Number(value) : 0;
              } else {
                newContent[contentField] = value;
              }
            } else if (stage.type === 'FILL_IN_BLANK') {
              if (!newContent.standardAnswers) {
                newContent = { question: '', standardAnswers: [], matchCase: false, points:0, ...newContent } as FillInBlankContent;
              }
              if (contentField === 'standardAnswers') {
                newContent.standardAnswers = typeof value === 'string' ? value.split(',').map((s: string) => s.trim()).filter((s: string) => s) : [];
              } else {
                newContent[contentField] = value;
              }
            } else if (stage.type === 'FILE_UPLOAD') {
               if (!newContent.prompt) {
                newContent = { prompt: '', points:0, ...newContent } as FileUploadContent;
              }
              newContent[contentField] = value;
            }
            updatedStage.content = newContent;
          } else {
            (updatedStage as any)[field as keyof Stage] = value;
            if (field === 'type') {
              let defaultContent: any;
              switch (value as Stage['type']) {
                case 'MULTIPLE_CHOICE': 
                  defaultContent = { 
                    question: '', options: [{ id: generateOptionId(), text: '' }, { id: generateOptionId(), text: '' }], correctAnswerId: null, points: 10, answerExplanation: '', explanationVisibleToStudent: false 
                  }; 
                  break;
                case 'FILL_IN_BLANK': 
                  defaultContent = { 
                    question: '', standardAnswers: [], matchCase: false, points: 5, answerExplanation: '', explanationVisibleToStudent: false 
                  }; 
                  break;
                case 'FILE_UPLOAD':
                  defaultContent = {
                    prompt: '', allowedFileTypes: '.pdf,.doc,.docx,.zip,.rar,.7z,.txt', maxFileSizeMB: 10, points: 10, answerExplanation: '', explanationVisibleToStudent: false
                  };
                  break;
                case 'CODE':
                  defaultContent = {
                    prompt: '', language: '', languageVersion: '', template: '// Code here', points: 0,
                    answerExplanation: '', explanationVisibleToStudent: false, testCases: []
                  } as CodeStageContent;
                  break;
                default:
                  updatedStage.content = { points: 10, answerExplanation: '', explanationVisibleToStudent: false, } as GeneralStageContent;
                  break; // ensure default path is handled or remove if not needed
              }
              updatedStage.content = defaultContent;
            }
          }
          return updatedStage;
        }
        return stage;
      })
    );
  }

  const handleAddOption = (stageIndex: number) => {
    setStages(prevStages => 
      prevStages.map((stage, i) => {
        if (i === stageIndex && stage.type === 'MULTIPLE_CHOICE') {
          const content = stage.content as MultipleChoiceContent;
          return {
            ...stage,
            content: {
              ...content,
              options: [...(content.options || []), { id: generateOptionId(), text: '' }],
            },
          };
        }
        return stage;
      })
    );
  }

  const handleRemoveOption = (stageIndex: number, optionIndex: number) => {
    setStages(prevStages =>
      prevStages.map((stage, i) => {
        if (i === stageIndex && stage.type === 'MULTIPLE_CHOICE') {
          const content = stage.content as MultipleChoiceContent;
          let newCorrectAnswerId = content.correctAnswerId;
          if (content.options[optionIndex]?.id === newCorrectAnswerId) {
            newCorrectAnswerId = null;
          }
          return {
            ...stage,
            content: {
              ...content,
              options: content.options.filter((_, idx) => idx !== optionIndex),
              correctAnswerId: newCorrectAnswerId,
            },
          };
        }
        return stage;
      })
    );
  }
  
  const handleSetCorrectAnswer = (stageIndex: number, optionId: string) => {
    handleStageChange(stageIndex, 'content.correctAnswerId', optionId);
  }

  // 学生选择相关函数
  const handleAddStudent = (student: Student) => {
    if (!selectedStudents.some(s => s.id === student.id)) {
      setSelectedStudents([...selectedStudents, student])
    }
    setSearchTerm('')
  }
  
  const handleRemoveStudent = (studentId: string) => {
    setSelectedStudents(selectedStudents.filter(s => s.id !== studentId))
  }
  
  const filteredStudents = students.filter(student => 
    !selectedStudents.some(s => s.id === student.id) && 
    (student.name?.toLowerCase().includes(searchTerm.toLowerCase()) || 
     student.email.toLowerCase().includes(searchTerm.toLowerCase()))
  )

  const validateForm = () => {
    if (!title.trim()) {
      toast.error('请输入实验标题')
      return false
    }
    if (!startTime) {
      toast.error('请选择开始时间')
      return false
    }
    if (!endTime) {
      toast.error('请选择结束时间')
      return false
    }
    if (new Date(startTime) >= new Date(endTime)) {
      toast.error('结束时间必须晚于开始时间')
      return false
    }
    if (stages.length === 0) {
      toast.error('请至少添加一个实验阶段')
      return false
    }
    for (const stage of stages) {
      if (!stage.title.trim()) {
        toast.error('请填写所有实验阶段的标题')
        return false
      }
    }
    return true
  }

  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    // 重置错误信息
    setErrorMsg(null)
    
    if (!validateForm()) {
      return
    }

    setIsSubmitting(true)
    
    const processedStages = stages.map(stage => {
      if (stage.type === 'CODE') {
        const codeContent = stage.content as CodeStageContent;
        if (!codeContent.language || !codeContent.languageVersion) {
          toast.error(`阶段 "${stage.title}" 未选择编程语言或版本。`);
          return null;
        }
      }
      return {
        ...stage,
        content: JSON.stringify(stage.content || {}),
      };
    }).filter(Boolean) as Stage[];
    
    const experimentData = {
      title,
      description,
      startTime,
      endTime,
      allowLateSubmission,
      stages: processedStages,
      authorizedStudents: selectedStudents.map((student: Student) => student.id)
    }
    
    console.log('提交实验数据:', experimentData)
    
    try {
      const response = await fetch('/api/experiments', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(experimentData),
        credentials: 'include',
      })
      
      console.log('API响应状态:', response.status, response.statusText)
      
      const responseData = await response.json()
      console.log('API响应数据:', responseData)

      if (!response.ok) {
        setErrorMsg(responseData.error || '创建实验失败')
        throw new Error(responseData.error || '创建实验失败')
      }

      toast.success('实验创建成功')
      try {
        const response = await fetch('/api/announcements', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            title: '您有新实验发布',
            content: title + '已经发布，请同学们尽快完成',
            experimentId: responseData.id,
          }),
        })

        if (!response.ok) {
          const data = await response.json()
          throw new Error(data.message || '创建公告失败')
        }

        toast.success('公告发布成功！')
      } catch (err: any) {
        setError(err.message || '创建公告失败，请稍后重试')
        toast.error(err.message || '创建公告失败')
      } finally {
        setLoading(false)
      }

      router.push('/experiments')
      router.refresh()
    } catch (error) {
      console.error('创建实验失败:', error)
      toast.error(error instanceof Error ? error.message : '创建实验失败，请重试')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 测试用例相关函数
  const handleAddTestCase = (stageIndex: number) => {
    setStages(prevStages => 
      prevStages.map((stage, i) => {
        if (i === stageIndex && stage.type === 'CODE') {
          const content = stage.content as CodeStageContent;
          const newTestCase: TestCase = {
            id: generateTestCaseId(),
            name: `测试 ${ (content.testCases?.length || 0) + 1}`,
            input: '',
            expectedOutput: '',
            points: 0,
            isHidden: false,
          };
          const newTestCases = [...(content.testCases || []), newTestCase];
          const newTotalPoints = calculateCodeStagePoints(newTestCases);
          return {
            ...stage,
            content: {
              ...content,
              testCases: newTestCases,
              points: newTotalPoints,
            },
          };
        }
        return stage;
      })
    );
  };

  const handleRemoveTestCase = (stageIndex: number, testCaseIdToRemove: string) => {
    setStages(prevStages =>
      prevStages.map((stage, i) => {
        if (i === stageIndex && stage.type === 'CODE') {
          const content = stage.content as CodeStageContent;
          const newTestCases = (content.testCases || []).filter(tc => tc.id !== testCaseIdToRemove);
          const newTotalPoints = calculateCodeStagePoints(newTestCases);
          return {
            ...stage,
            content: {
              ...content,
              testCases: newTestCases,
              points: newTotalPoints,
            },
          };
        }
        return stage;
      })
    );
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-8">
      {errorMsg && (
        <div className="bg-red-50 border border-red-300 text-red-700 px-4 py-3 rounded">
          <p className="font-medium">创建失败</p>
          <p className="text-sm">{errorMsg}</p>
        </div>
      )}
      
      <div className="space-y-6 bg-white p-6 rounded-lg shadow">
        <div>
          <label htmlFor="title" className="block text-sm font-medium text-gray-700">
            实验标题
          </label>
          <input
            type="text"
            name="title"
            id="title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
            required
          />
        </div>

        <div>
          <label htmlFor="description" className="block text-sm font-medium text-gray-700">
            实验描述
          </label>
          <textarea
            id="description"
            name="description"
            rows={3}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
          />
        </div>

        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
          <div>
            <label htmlFor="startTime" className="block text-sm font-medium text-gray-700">
              开始时间
            </label>
            <input
              type="datetime-local"
              name="startTime"
              id="startTime"
              value={startTime}
              onChange={(e) => setStartTime(e.target.value)}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
              required
            />
          </div>

          <div>
            <label htmlFor="endTime" className="block text-sm font-medium text-gray-700">
              结束时间
            </label>
            <input
              type="datetime-local"
              name="endTime"
              id="endTime"
              value={endTime}
              onChange={(e) => setEndTime(e.target.value)}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
              required
            />
          </div>
        </div>

        <div className="flex items-center">
          <input
            id="allowLateSubmission"
            name="allowLateSubmission"
            type="checkbox"
            checked={allowLateSubmission}
            onChange={(e) => setAllowLateSubmission(e.target.checked)}
            className="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
          />
          <label htmlFor="allowLateSubmission" className="ml-2 block text-sm text-gray-900">
            允许截止后提交
          </label>
        </div>
      </div>
      
      {/* 添加学生授权部分 */}
      <div className="space-y-6 bg-white p-6 rounded-lg shadow">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-medium text-gray-900">授权学生</h3>
          <Button
            type="button"
            variant="outline"
            onClick={() => setShowStudentSearch(!showStudentSearch)}
            className="inline-flex items-center"
          >
            <UserPlusIcon className="h-5 w-5 mr-1" />
            {showStudentSearch ? '取消添加' : '添加学生'}
          </Button>
        </div>
        
        {showStudentSearch && (
          <div className="mt-4">
            <label htmlFor="studentSearch" className="block text-sm font-medium text-gray-700">
              搜索学生
            </label>
            <div className="mt-1 relative">
              <input
                type="text"
                id="studentSearch"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="输入姓名或邮箱搜索"
                className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md"
              />
              {searchTerm && filteredStudents.length > 0 && (
                <div className="absolute z-10 mt-1 w-full bg-white shadow-lg max-h-60 rounded-md overflow-auto">
                  <ul className="divide-y divide-gray-200">
                    {filteredStudents.map(student => (
                      <li 
                        key={student.id} 
                        className="px-4 py-2 hover:bg-gray-100 cursor-pointer"
                        onClick={() => handleAddStudent(student)}
                      >
                        <div className="flex items-center">
                          <div>
                            <p className="text-sm font-medium text-gray-900">{student.name}</p>
                            <p className="text-sm text-gray-500">{student.email}</p>
                          </div>
                        </div>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          </div>
        )}
        
        <div className="mt-4">
          {selectedStudents.length === 0 ? (
            <p className="text-sm text-gray-500">未指定授权学生，默认仅自己可见或根据后续设置。</p>
          ) : (
            <div className="flex flex-wrap gap-2">
              {selectedStudents.map(student => (
                <div
                  key={student.id}
                  className="inline-flex items-center bg-gray-100 rounded-full px-3 py-1 text-sm"
                >
                  <span className="truncate">{student.name || student.email}</span>
                  <button
                    type="button"
                    onClick={() => handleRemoveStudent(student.id)}
                    className="ml-1 text-gray-500 hover:text-gray-700"
                  >
                    <XMarkIcon className="h-4 w-4" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="space-y-6 bg-white p-6 rounded-lg shadow">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-medium text-gray-900">实验阶段</h3>
          <Button
            type="button"
            variant="outline"
            onClick={handleAddStage}
            className="inline-flex items-center"
          >
            <PlusIcon className="h-5 w-5 mr-1" />
            添加阶段
          </Button>
        </div>

        <div className="space-y-6">
          {stages.map((stage, stageIndex) => (
            <div key={stageIndex} className="border rounded-lg p-4 relative space-y-4">
              <button
                type="button"
                onClick={() => handleRemoveStage(stageIndex)}
                className="absolute top-3 right-3 text-gray-400 hover:text-gray-600 p-1"
              >
                <TrashIcon className="h-5 w-5" />
              </button>

              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    阶段标题
                  </label>
                  <input
                    type="text"
                    value={stage.title}
                    onChange={(e) => handleStageChange(stageIndex, 'title', e.target.value)}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    阶段类型
                  </label>
                  <select
                    value={stage.type}
                    onChange={(e) => {
                      const newType = e.target.value as Stage['type'];
                      handleStageChange(stageIndex, 'type', newType);
                    }}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                  >
                    <option value="MULTIPLE_CHOICE">选择题</option>
                    <option value="FILL_IN_BLANK">填空题</option>
                    <option value="CODE">代码题</option>
                    <option value="FILE_UPLOAD">文件上传</option>
                  </select>
                </div>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700">
                  阶段描述/说明
                </label>
                <textarea
                  value={stage.description}
                  onChange={(e) => handleStageChange(stageIndex, 'description', e.target.value)}
                  rows={2}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                  placeholder="对这个阶段的整体说明或指导"
                />
              </div>

              {/* Conditional rendering for MULTIPLE_CHOICE type */}
              {stage.type === 'MULTIPLE_CHOICE' && stage.content && (
                <div className="border-t border-gray-200 pt-4 mt-4 space-y-4">
                  <h4 className="text-md font-medium text-gray-800">选择题内容:</h4>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-mc-question`} className="block text-sm font-medium text-gray-700">
                      题目 <span className="text-red-500">*</span>
                    </label>
                    <textarea
                      id={`stage-${stageIndex}-mc-question`}
                      value={(stage.content as MultipleChoiceContent).question}
                      onChange={(e) => handleStageChange(stageIndex, 'content.question', e.target.value)}
                      rows={3}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder="输入选择题的题干"
                      required
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700">
                      选项 <span className="text-red-500">*</span> (至少2个)
                    </label>
                    <div className="mt-2 space-y-3">
                      {(stage.content as MultipleChoiceContent).options.map((option, optionIndex) => (
                        <div key={option.id || optionIndex} className="flex items-center space-x-3">
                          <input
                            type="radio"
                            name={`stage-${stageIndex}-correctAnswer`}
                            id={`stage-${stageIndex}-option-${option.id}`}
                            checked={(stage.content as MultipleChoiceContent).correctAnswerId === option.id}
                            onChange={(e) => handleStageChange(stageIndex, `content.options.${optionIndex}.text`, e.target.value)}
                            className="h-4 w-4 text-primary-600 border-gray-300 focus:ring-primary-500"
                          />
                          <input
                            type="text"
                            value={option.text}
                            onChange={(e) => handleStageChange(stageIndex, `content.options.${optionIndex}.text`, e.target.value)}
                            placeholder={`选项 ${optionIndex + 1}`}
                            className="flex-grow block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                            required
                          />
                          {(stage.content as MultipleChoiceContent).options.length > 2 && (
                             <button
                                type="button"
                                onClick={() => handleRemoveOption(stageIndex, optionIndex)}
                                className="text-gray-400 hover:text-red-600 p-1 rounded-full hover:bg-red-50"
                                title="删除此选项"
                              >
                                <XMarkIcon className="h-5 w-5" />
                              </button>
                          )}
                        </div>
                      ))}
                    </div>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => handleAddOption(stageIndex)}
                      className="mt-2 text-primary-600 hover:text-primary-800"
                    >
                      <PlusIcon className="h-4 w-4 mr-1" /> 添加选项
                    </Button>
                  </div>
                  
                  <div>
                    <label htmlFor={`stage-${stageIndex}-mc-points`} className="block text-sm font-medium text-gray-700">
                      分值
                    </label>
                    <input
                      type="number"
                      id={`stage-${stageIndex}-mc-points`}
                      value={(stage.content as MultipleChoiceContent).points || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.points', parseInt(e.target.value, 10))}
                      className="mt-1 block w-1/4 rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      min="0"
                      placeholder="例如: 10"
                    />
                  </div>
                </div>
              )}
              {/* End of MULTIPLE_CHOICE specific content */}

              {/* Conditional rendering for FILL_IN_BLANK type */}
              {stage.type === 'FILL_IN_BLANK' && (
                <div className="border-t border-gray-200 pt-4 mt-4 space-y-4">
                  <h4 className="text-md font-medium text-gray-800">填空题内容:</h4>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fib-question`} className="block text-sm font-medium text-gray-700">
                      题干/说明 (用 "__" 表示填空处，可选)
                    </label>
                    <textarea
                      id={`stage-${stageIndex}-fib-question`}
                      value={(stage.content as FillInBlankContent)?.question || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.question', e.target.value)}
                      rows={3}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder="例如：地球的唯一天然卫星是 __ 。"
                    />
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fib-answers`} className="block text-sm font-medium text-gray-700">
                      标准答案 (多个答案请用英文逗号 "," 分隔) <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id={`stage-${stageIndex}-fib-answers`}
                      value={((stage.content as FillInBlankContent)?.standardAnswers || []).join(',')}
                      onChange={(e) => handleStageChange(stageIndex, 'content.standardAnswers', e.target.value)}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder="例如：月球,月亮"
                      required
                    />
                  </div>
                  <div className="flex items-center">
                    <input
                      type="checkbox"
                      id={`stage-${stageIndex}-fib-matchcase`}
                      checked={(stage.content as FillInBlankContent)?.matchCase || false}
                      onChange={(e) => handleStageChange(stageIndex, 'content.matchCase', e.target.checked)}
                      className="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                    />
                    <label htmlFor={`stage-${stageIndex}-fib-matchcase`} className="ml-2 block text-sm text-gray-900">
                      匹配时区分大小写
                    </label>
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fib-points`} className="block text-sm font-medium text-gray-700">
                      分值
                    </label>
                    <input
                      type="number"
                      id={`stage-${stageIndex}-fib-points`}
                      value={(stage.content as FillInBlankContent)?.points || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.points', parseInt(e.target.value, 10))}
                      className="mt-1 block w-1/4 rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      min="0"
                      placeholder="例如: 5"
                    />
                  </div>
                 </div>
              )}
              {/* End of FILL_IN_BLANK specific content */}

              {/* Conditional rendering for FILE_UPLOAD type */}
              {stage.type === 'FILE_UPLOAD' && (
                <div className="border-t border-gray-200 pt-4 mt-4 space-y-4">
                  <h4 className="text-md font-medium text-gray-800">文件上传题设置:</h4>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fu-prompt`} className="block text-sm font-medium text-gray-700">
                      题干 / 提交说明与要求 <span className="text-red-500">*</span>
                    </label>
                    <textarea
                      id={`stage-${stageIndex}-fu-prompt`}
                      value={(stage.content as FileUploadContent)?.prompt || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.prompt', e.target.value)}
                      rows={3}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder="例如：请上传您的实验报告，包含xxx和yyy部分。文件格式为PDF。"
                      required
                    />
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fu-filetypes`} className="block text-sm font-medium text-gray-700">
                      允许的文件类型 (英文逗号分隔, 如: .pdf,.docx,.zip)
                    </label>
                    <input
                      type="text"
                      id={`stage-${stageIndex}-fu-filetypes`}
                      value={(stage.content as FileUploadContent)?.allowedFileTypes || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.allowedFileTypes', e.target.value)}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder=".pdf,.doc,.docx,.zip,.txt"
                    />
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fu-maxsize`} className="block text-sm font-medium text-gray-700">
                      最大文件大小 (MB)
                    </label>
                    <input
                      type="number"
                      id={`stage-${stageIndex}-fu-maxsize`}
                      value={(stage.content as FileUploadContent)?.maxFileSizeMB || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.maxFileSizeMB', e.target.value ? parseInt(e.target.value, 10) : undefined)}
                      className="mt-1 block w-1/4 rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      min="1"
                      placeholder="例如: 10"
                    />
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fu-points`} className="block text-sm font-medium text-gray-700">
                      分值
                    </label>
                    <input
                      type="number"
                      id={`stage-${stageIndex}-fu-points`}
                      value={(stage.content as FileUploadContent)?.points || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.points', parseInt(e.target.value, 10))}
                      className="mt-1 block w-1/4 rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      min="0"
                      placeholder="例如: 20"
                    />
                  </div>
                 </div>
              )}
              {/* End of FILE_UPLOAD specific content */}

              {/* Conditional rendering for CODE type */}
              {stage.type === 'CODE' && (
                <div className="border-t border-gray-200 pt-4 mt-4 space-y-4">
                  <h4 className="text-md font-medium text-gray-800">代码题设置:</h4>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-code-prompt`} className="block text-sm font-medium text-gray-700">题干 / 编程要求 <span className="text-red-500">*</span></label>
                    <textarea
                      id={`stage-${stageIndex}-code-prompt`}
                      value={(stage.content as CodeStageContent)?.prompt || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.prompt', e.target.value)}
                      rows={4}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder="详细描述编程任务、输入输出格式、约束条件等。"
                      required
                    />
                 </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-piston-language`} className="block text-sm font-medium text-gray-700">编程语言 <span className="text-red-500">*</span></label>
                    <select
                      id={`stage-${stageIndex}-piston-language`}
                      value={(stage.content as CodeStageContent)?.language || ''}
                      disabled={isLoadingRuntimes}
                      onChange={(e) => handleStageChange(stageIndex, 'content.language', e.target.value)}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      required
                    >
                      <option value="">{isLoadingRuntimes ? "加载中..." : "选择语言"}</option>
                      {!isLoadingRuntimes &&
                        Array.from(new Set(pistonRuntimes.map((rt: PistonRuntime) => rt.language))).sort().map((lang: string) => (
                          <option key={lang} value={lang}>{lang}</option>
                        ))}
                    </select>
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-piston-version`} className="block text-sm font-medium text-gray-700">语言版本 <span className="text-red-500">*</span></label>
                    <select
                      id={`stage-${stageIndex}-piston-version`}
                      value={(stage.content as CodeStageContent)?.languageVersion || ''}
                      disabled={isLoadingRuntimes || !(stage.content as CodeStageContent)?.language}
                      onChange={(e) => handleStageChange(stageIndex, 'content.languageVersion', e.target.value)}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      required
                    >
                      <option value="">
                        {isLoadingRuntimes ? "加载中..." : 
                          (!(stage.content as CodeStageContent)?.language ? "请先选择语言" : "选择版本")}
                      </option>
                      {!isLoadingRuntimes && (stage.content as CodeStageContent)?.language &&
                        pistonRuntimes
                          .filter(rt => rt.language === (stage.content as CodeStageContent).language)
                          .sort((a,b) => b.version.localeCompare(a.version, undefined, { numeric: true }))
                          .map(rt => (
                            <option key={`${rt.language}-${rt.version}`} value={rt.version}>
                              {rt.version}{rt.aliases && rt.aliases.length > 0 ? ` (${rt.aliases.join(', ')})` : ''}
                            </option>
                          ))}
                    </select>
                    { stage.type ==='CODE' && (!(stage.content as CodeStageContent)?.language || !(stage.content as CodeStageContent)?.languageVersion) && (
                        <p className="text-xs text-red-500 mt-1">编程题必须选择语言和对应的版本。</p>
                    )}
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-code-template`} className="block text-sm font-medium text-gray-700">代码模板 (可选)</label>
                    <textarea
                      id={`stage-${stageIndex}-code-template`}
                      value={(stage.content as CodeStageContent)?.template || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.template', e.target.value)}
                      rows={6}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm font-mono"
                      placeholder="// 在此编写您的代码模板&#10;// 例如：&#10;function main() {&#10;  // 请在此处实现功能&#10;}"
                    />
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-code-points`} className="block text-sm font-medium text-gray-700">分值 (自动计算)</label>
                    <input
                      type="number"
                      id={`stage-${stageIndex}-code-points`}
                      value={(stage.content as CodeStageContent)?.points || 0}
                      readOnly
                      className="mt-1 block w-1/4 rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm bg-gray-100"
                      placeholder="0"
                    />
                  </div>

                  {/* 测试用例配置区域开始 */}
                  <div className="border-t border-gray-200 pt-4 mt-6">
                    <div className="flex justify-between items-center mb-3">
                      <h5 className="text-md font-medium text-gray-800">测试用例:</h5>
                      <Button 
                        type="button" 
                        variant="outline"
                        size="sm"
                        onClick={() => handleAddTestCase(stageIndex)}
                      >
                        <PlusIcon className="h-4 w-4 mr-1" /> 添加测试用例
                      </Button>
                    </div>
                    
                    {(stage.content as CodeStageContent).testCases && 
                      Array.isArray((stage.content as CodeStageContent).testCases) && 
                      ((stage.content as CodeStageContent).testCases as TestCase[]).length > 0 ? (
                      <div className="space-y-4">
                        {((stage.content as CodeStageContent).testCases as TestCase[]).map((testCase, tcIndex) => (
                          <div key={testCase.id} className="border rounded-md p-3 bg-gray-50 space-y-3">
                            <div className="flex justify-between items-center">
                              <input 
                                type="text"
                                value={testCase.name}
                                placeholder={`测试用例 ${tcIndex + 1} 名称`}
                                onChange={(e) => handleStageChange(stageIndex, 'content.testCases', e.target.value, tcIndex, 'name')}
                                className="text-sm font-medium p-1 border-b border-gray-300 focus:border-primary-500 outline-none flex-grow"
                              />
                              <button
                                type="button"
                                onClick={() => handleRemoveTestCase(stageIndex, testCase.id)}
                                className="text-red-500 hover:text-red-700 p-1 ml-2"
                                title="删除此测试用例"
                              >
                                <TrashIcon className="h-4 w-4" />
                              </button>
                            </div>

                            <div>
                              <label htmlFor={`stage-${stageIndex}-tc-${tcIndex}-input`} className="block text-xs font-medium text-gray-600">输入 (Input):</label>
                              <textarea 
                                id={`stage-${stageIndex}-tc-${tcIndex}-input`}
                                value={testCase.input}
                                onChange={(e) => handleStageChange(stageIndex, 'content.testCases', e.target.value, tcIndex, 'input')}
                                rows={2}
                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm font-mono text-xs"
                                placeholder="测试用例的输入数据..."
                              />
                            </div>
                            <div>
                              <label htmlFor={`stage-${stageIndex}-tc-${tcIndex}-output`} className="block text-xs font-medium text-gray-600">预期输出 (Expected Output):</label>
                              <textarea 
                                id={`stage-${stageIndex}-tc-${tcIndex}-output`}
                                value={testCase.expectedOutput}
                                onChange={(e) => handleStageChange(stageIndex, 'content.testCases', e.target.value, tcIndex, 'expectedOutput')}
                                rows={2}
                                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm font-mono text-xs"
                                placeholder="期望的输出结果..."
                              />
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label htmlFor={`stage-${stageIndex}-tc-${tcIndex}-points`} className="block text-xs font-medium text-gray-600">分值:</label>
                                    <input 
                                        type="number"
                                        id={`stage-${stageIndex}-tc-${tcIndex}-points`}
                                        value={testCase.points}
                                        onChange={(e) => handleStageChange(stageIndex, 'content.testCases', parseInt(e.target.value, 10) || 0, tcIndex, 'points')}
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                                        min="0"
                                    />
                                </div>
                                <div className="flex items-end pb-1">
                                    <input 
                                        type="checkbox"
                                        id={`stage-${stageIndex}-tc-${tcIndex}-hidden`}
                                        checked={testCase.isHidden}
                                        onChange={(e) => handleStageChange(stageIndex, 'content.testCases', e.target.checked, tcIndex, 'isHidden')}
                                        className="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                                    />
                                    <label htmlFor={`stage-${stageIndex}-tc-${tcIndex}-hidden`} className="ml-2 text-xs font-medium text-gray-600">对学生隐藏输入/输出</label>
                                </div>
                            </div>
            </div>
          ))}
        </div>
                    ) : (
                      <p className="text-xs text-gray-500 text-center py-2">暂无测试用例，点击上方按钮添加。</p>
                    )}
                  </div>
                  {/* 测试用例配置区域结束 */}
                </div>
              )}
              {/* End of CODE specific content */}

              {/* Common fields for answer explanation and visibility for all types */}
              <div className="border-t border-gray-200 pt-4 mt-4 space-y-4">
                <div>
                  <label htmlFor={`stage-${stageIndex}-explanation`} className="block text-sm font-medium text-gray-700">
                    答案解析/说明
                  </label>
                  <textarea
                    id={`stage-${stageIndex}-explanation`}
                    value={(stage.content as GeneralStageContent)?.answerExplanation || ''}
                    onChange={(e) => handleStageChange(stageIndex, 'content.answerExplanation', e.target.value)}
                    rows={4}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                    placeholder="输入该阶段的答案解析、评分标准或参考思路。"
                  />
                </div>
                <div className="flex items-center">
                  <input
                    type="checkbox"
                    id={`stage-${stageIndex}-explanation-visible`}
                    checked={(stage.content as GeneralStageContent)?.explanationVisibleToStudent || false}
                    onChange={(e) => handleStageChange(stageIndex, 'content.explanationVisibleToStudent', e.target.checked)}
                    className="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                  />
                  <label htmlFor={`stage-${stageIndex}-explanation-visible`} className="ml-2 block text-sm text-gray-900">
                    提交后对学生可见此解析
                  </label>
                </div>
              </div>

            </div>
          ))}
        </div>
      </div>

      <div className="flex justify-end space-x-4 pt-5">
        <Button
          type="button"
          variant="outline"
          onClick={() => router.back()}
          disabled={isSubmitting}
        >
          取消
        </Button>
        <Button type="submit" disabled={isSubmitting} className="min-w-[100px]">
          {isSubmitting ? '创建中...' : '创建实验'}
        </Button>
      </div>
    </form>
  )
} 